<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="分类名称" prop="categoryName">
        <el-input
          v-model="queryParams.categoryName"
          placeholder="请输入分类名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否免费" prop="isFree">
        <el-select v-model="queryParams.isFree" placeholder="请选择" clearable>
          <el-option label="免费" :value="1" />
          <el-option label="付费" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item label="显示状态" prop="isVisible">
        <el-select v-model="queryParams.isVisible" placeholder="请选择显示状态" clearable">
          <el-option label="显示" :value="1" />
          <el-option label="隐藏" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['video:category:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['video:category:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['video:category:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="categoryList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="分类ID" align="center" prop="categoryId" width="80" />
      <el-table-column label="分类图标" align="center" width="80">
        <template slot-scope="scope">
          <span style="font-size: 32px;">{{ scope.row.categoryIcon }}</span>
        </template>
      </el-table-column>
      <el-table-column label="分类名称" align="center" prop="categoryName" :show-overflow-tooltip="true" />
      <el-table-column label="分类描述" align="center" prop="categoryDescription" :show-overflow-tooltip="true" />
      <el-table-column label="类型" align="center" prop="isFree" width="80">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.isFree === 1" type="success">免费</el-tag>
          <el-tag v-else type="warning">付费</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="排序" align="center" prop="sortOrder" width="80" />
      <el-table-column label="视频数" align="center" prop="videoCount" width="80" />
      <el-table-column label="播放量" align="center" prop="totalViews" width="100">
        <template slot-scope="scope">
          {{ formatNumber(scope.row.totalViews) }}
        </template>
      </el-table-column>
      <el-table-column label="收入" align="center" prop="totalRevenue" width="100">
        <template slot-scope="scope">
          <span style="color: #f56c6c; font-weight: bold;">¥{{ scope.row.totalRevenue }}</span>
        </template>
      </el-table-column>
      <el-table-column label="显示状态" align="center" width="80">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.isVisible"
            :active-value="1"
            :inactive-value="0"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['video:category:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-video-camera"
            @click="handleBindVideo(scope.row)"
            v-hasPermi="['video:category:edit']"
          >绑定视频</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['video:category:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改分类对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="分类名称" prop="categoryName">
          <el-input v-model="form.categoryName" placeholder="请输入分类名称" maxlength="50" />
        </el-form-item>
        <el-form-item label="分类描述" prop="categoryDescription">
          <el-input v-model="form.categoryDescription" type="textarea" placeholder="请输入分类描述" maxlength="200" />
        </el-form-item>
        <el-form-item label="分类图标" prop="categoryIcon">
          <el-select v-model="form.categoryIcon" placeholder="请选择分类图标">
            <el-option label="🎬 电影" value="🎬" />
            <el-option label="🔥 热门" value="🔥" />
            <el-option label="💥 动作" value="💥" />
            <el-option label="😄 喜剧" value="😄" />
            <el-option label="💕 爱情" value="💕" />
            <el-option label="🚀 科幻" value="🚀" />
            <el-option label="👻 恐怖" value="👻" />
            <el-option label="📹 纪录" value="📹" />
            <el-option label="🔍 悬疑" value="🔍" />
            <el-option label="⚔️ 战争" value="⚔️" />
            <el-option label="🎨 动画" value="🎨" />
            <el-option label="👘 古装" value="👘" />
            <el-option label="🏙️ 现代" value="🏙️" />
            <el-option label="🎭 港台" value="🎭" />
            <el-option label="🇰🇷 韩剧" value="🇰🇷" />
            <el-option label="🇺🇸 美剧" value="🇺🇸" />
          </el-select>
        </el-form-item>
        <el-form-item label="是否免费" prop="isFree">
          <el-radio-group v-model="form.isFree">
            <el-radio :label="1">免费</el-radio>
            <el-radio :label="0">付费</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="排序权重" prop="sortOrder">
          <el-input-number v-model="form.sortOrder" controls-position="right" :min="0" :max="999" />
          <span style="color: #909399; font-size: 12px; margin-left: 10px;">数字越大越靠前</span>
        </el-form-item>
        <el-form-item label="显示状态" prop="isVisible">
          <el-radio-group v-model="form.isVisible">
            <el-radio :label="1">显示</el-radio>
            <el-radio :label="0">隐藏</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 绑定视频对话框 -->
    <el-dialog title="绑定视频" :visible.sync="bindOpen" width="900px" append-to-body>
      <div style="margin-bottom: 20px;">
        <el-alert
          :title="`为分类「${currentCategory.categoryName}」绑定视频`"
          type="info"
          :closable="false"
          show-icon>
        </el-alert>
      </div>
      
      <!-- 统计信息 -->
      <el-row :gutter="20" style="margin-bottom: 20px;">
        <el-col :span="8">
          <el-card shadow="hover">
            <div style="text-align: center;">
              <div style="font-size: 24px; color: #409EFF; font-weight: bold;">{{ videoList.length }}</div>
              <div style="color: #909399; font-size: 12px;">总视频数</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card shadow="hover">
            <div style="text-align: center;">
              <div style="font-size: 24px; color: #67C23A; font-weight: bold;">{{ selectedVideos.length }}</div>
              <div style="color: #909399; font-size: 12px;">已选视频</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card shadow="hover">
            <div style="text-align: center;">
              <div style="font-size: 24px; color: #E6A23C; font-weight: bold;">{{ video4KCount }}</div>
              <div style="color: #909399; font-size: 12px;">4K视频</div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 视频选择列表 -->
      <el-table
        ref="videoTable"
        :data="videoList"
        @selection-change="handleVideoSelection"
        max-height="400"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="视频ID" align="center" prop="videoId" width="80" />
        <el-table-column label="视频标题" align="center" prop="title" :show-overflow-tooltip="true" />
        <el-table-column label="画质" align="center" prop="quality" width="80">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.quality === '4K'" type="danger">4K</el-tag>
            <el-tag v-else-if="scope.row.quality === 'HD'" type="success">HD</el-tag>
            <el-tag v-else type="info">SD</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="时长" align="center" prop="duration" width="100" />
        <el-table-column label="价格" align="center" prop="price" width="100">
          <template slot-scope="scope">
            <span v-if="scope.row.price === 0" style="color: #67C23A;">免费</span>
            <span v-else style="color: #f56c6c; font-weight: bold;">¥{{ scope.row.price }}</span>
          </template>
        </el-table-column>
      </el-table>

      <div slot="footer" class="dialog-footer">
        <el-button @click="bindOpen = false">取 消</el-button>
        <el-button type="warning" @click="selectedVideos = []">清空选择</el-button>
        <el-button type="primary" @click="submitBindVideos">确定绑定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCategory, getCategory, delCategory, addCategory, updateCategory, getCategoryVideos, bindVideos } from "@/api/video/category";

export default {
  name: "Category",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 分类表格数据
      categoryList: [],
      // 视频列表
      videoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 绑定视频对话框
      bindOpen: false,
      // 当前分类
      currentCategory: {},
      // 已选视频
      selectedVideos: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        categoryName: null,
        isFree: null,
        isVisible: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        categoryName: [
          { required: true, message: "分类名称不能为空", trigger: "blur" }
        ],
        sortOrder: [
          { required: true, message: "排序权重不能为空", trigger: "blur" }
        ]
      }
    };
  },
  computed: {
    video4KCount() {
      return this.selectedVideos.filter(v => v.quality === '4K').length;
    }
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询分类列表 */
    getList() {
      this.loading = true;
      listCategory(this.queryParams).then(response => {
        this.categoryList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 格式化数字 */
    formatNumber(num) {
      if (num >= 10000) {
        return (num / 10000).toFixed(1) + '万';
      }
      return num;
    },
    /** 视频选择变化 */
    handleVideoSelection(selection) {
      this.selectedVideos = selection;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        categoryId: null,
        categoryName: null,
        categoryIcon: "🎬",
        categoryDescription: null,
        sortOrder: 0,
        isVisible: 1,
        isFree: 0,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.categoryId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加视频分类";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const categoryId = row.categoryId || this.ids
      getCategory(categoryId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改视频分类";
      });
    },
    /** 绑定视频操作 */
    handleBindVideo(row) {
      this.currentCategory = row;
      this.bindOpen = true;
      // 这里暂时使用模拟数据，实际应该调用视频列表接口
      this.videoList = [
        { videoId: 1, title: '速度与激情10', quality: '4K', duration: '142:30', price: 19.9 },
        { videoId: 2, title: '流浪地球3', quality: '4K', duration: '158:45', price: 24.9 },
        { videoId: 3, title: '满江红', quality: 'HD', duration: '126:20', price: 15.9 },
      ];
      // 加载已绑定的视频
      getCategoryVideos(row.categoryId).then(response => {
        const boundIds = response.data || [];
        this.$nextTick(() => {
          this.videoList.forEach(video => {
            if (boundIds.includes(video.videoId)) {
              this.$refs.videoTable.toggleRowSelection(video, true);
            }
          });
        });
      });
    },
    /** 提交绑定视频 */
    submitBindVideos() {
      const videoIds = this.selectedVideos.map(v => v.videoId);
      bindVideos(this.currentCategory.categoryId, videoIds).then(response => {
        this.$modal.msgSuccess("绑定成功");
        this.bindOpen = false;
        this.getList();
      });
    },
    /** 状态切换 */
    handleStatusChange(row) {
      let text = row.isVisible === 1 ? "显示" : "隐藏";
      this.$modal.confirm('确认要将分类"' + row.categoryName + '"设置为' + text + '状态吗？').then(function() {
        return updateCategory(row);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function() {
        row.isVisible = row.isVisible === 0 ? 1 : 0;
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.categoryId != null) {
            updateCategory(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCategory(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const categoryIds = row.categoryId || this.ids;
      this.$modal.confirm('是否确认删除分类编号为"' + categoryIds + '"的数据项？').then(function() {
        return delCategory(categoryIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    }
  }
};
</script>

<style scoped>
</style>

